﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SmartParkingServer.Models;
using System;
using System.Globalization;
using System.Linq;

namespace SmartParkingServer.EFCore
{
    public class EFCoreContext : DbContext
    {
        /// <summary>
        /// 配置数据库的连接
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=CHINAMI-P3HMT1O;Database=SP_2022;Trusted_Connection=True");//信任连接
        }
         
        /// <summary>
        /// 对接数据库   用户数据    DBContext  声明一个对应的集合对象
        /// </summary>
        public DbSet<UserModel> Users { get; set; }
        public DbSet<UpgradeFileModel> UpgradeFileModel { get; set; }



        #region 转换器  数据库中时间转换  string<->timespan
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 文件库中时间转换  string<->timespan
            /// 1、创建了ValueConverter对象实例
            /// 2、构造函数两个参数（两个委托）
            ///     -  第一个委托是从第一个泛型类型转换到第二个泛型
            ///     -  第二个委托   反相操作
            ValueConverter timeValueConverter = new ValueConverter<string, long>
                (
                str => TimeValueFromString(str),
                ts => TimeValueFromLong(ts)
                );


            // 配置到EFCore中
            modelBuilder.Entity<UpgradeFileModel>().Property(p => p.UploadTime).HasConversion(timeValueConverter);

            // 菜单表中字体图标值转换   编号string<->字符string
            ValueConverter iconValueConverter = new ValueConverter<string, string>(

                v => string.IsNullOrEmpty(v) ? null : ((int)v.ToArray()[0]).ToString("x"),//转16进制

                v => v == null ? "" : ((char)int.Parse(v, NumberStyles.HexNumber)).ToString()

                );
            modelBuilder.Entity<MenuModel>().Property(p => p.MenuIcon).HasConversion(iconValueConverter);

            // (char)64
        }

        /// <summary>
        /// /
        /// </summary>
        /// <param name="time">2022-01-24 20:00:00</param>
        /// <returns></returns>
        private long TimeValueFromString(string time)
        {
            // C#进行获取时间戳的方式
            return (DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).Ticks - 621355968000000000) / 10000000;
        }

        private string TimeValueFromLong(long time)
        {
            return new DateTime(time * 10000000 + 621355968000000000).ToString("yyyy-MM-dd HH:mm:ss");
        } 
        #endregion
    }
}
